package com.wust.modules.online.cgform.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import com.wust.common.system.api.SysBaseApi;
import com.wust.common.util.oConvertUtils;
import com.wust.modules.online.cgform.entity.OnlCgformButton;
import com.wust.modules.online.cgform.entity.OnlCgformEnhanceJs;
import com.wust.modules.online.cgform.entity.OnlCgformField;
import com.wust.modules.online.cgform.entity.OnlCgformHead;
import com.wust.modules.online.cgform.model.*;
import com.wust.modules.online.cgform.util.EnhanceJsUtil;
import com.wust.modules.online.cgform.util.SqlSymbolUtil;
import org.apache.commons.lang.StringUtils;
import com.wust.modules.online.cgform.service.IOnlCgformFieldService;
import com.wust.modules.online.cgform.service.IOnlCgformHeadService;
import com.wust.modules.online.cgform.model.LinkDown;
import com.wust.modules.online.cgform.service.IOnlineService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author wanheng
 */
@Service
public class OnlineServiceImpl implements IOnlineService {

    @Resource
    private IOnlCgformFieldService onlCgformFieldService;
    @Resource
    private IOnlCgformHeadService onlCgformHeadService;
    @Resource
    private SysBaseApi sysBaseAPI;


    @Override
    public OnlineConfigModel queryOnlineConfig(OnlCgformHead onlCgformHead) {
        String onlCgformHeadId = onlCgformHead.getId();
        List onlCgformFields = this.getOnlCgformField(onlCgformHeadId);
        List onlineHideColumns = this.onlCgformFieldService.selectOnlineHideColumns(onlCgformHead.getTableName());
        ArrayList arrayList = new ArrayList();
        HashMap hashMap = new HashMap();
        ArrayList arrayList1 = new ArrayList();
        ArrayList arrayList2 = new ArrayList();
        ArrayList arrayList3 = new ArrayList();
        Iterator iterator = onlCgformFields.iterator();

        String s;
        while(iterator.hasNext()) {
            OnlCgformField onlCgformField = (OnlCgformField) iterator.next();
            String dbFieldName = onlCgformField.getDbFieldName();
            String mainTable = onlCgformField.getMainTable();
            s = onlCgformField.getMainField();
            if (oConvertUtils.isNotEmpty(s) && oConvertUtils.isNotEmpty(mainTable)) {
                KeyModel keyModel = new KeyModel(dbFieldName, s);
                arrayList2.add(keyModel);
            }

            if (1 == onlCgformField.getIsShowList() && !"id".equals(dbFieldName) && !onlineHideColumns.contains(dbFieldName) && !arrayList3.contains(dbFieldName)) {
                ColumnModel columnModel = new ColumnModel(onlCgformField.getDbFieldTxt(), dbFieldName);
                String dictField = onlCgformField.getDictField();
                String showType = onlCgformField.getFieldShowType();
                if (oConvertUtils.isNotEmpty(dictField) && !"popup".equals(showType)) {
                    Object arrayList4 = new ArrayList();
                    if (oConvertUtils.isNotEmpty(onlCgformField.getDictTable())) {
                        arrayList4 = this.sysBaseAPI.queryTableDictItemsByCode(onlCgformField.getDictTable(), onlCgformField.getDictText(), dictField);
                    } else if (oConvertUtils.isNotEmpty(onlCgformField.getDictField())) {
                        arrayList4 = this.sysBaseAPI.queryDictItemsByCode(dictField);
                    }

                    hashMap.put(dbFieldName, arrayList4);
                    columnModel.setCustomRender(dbFieldName);
                }

                List list;
                String s1;
                if ("link_down".equals(showType)) {
                    s1 = onlCgformField.getDictTable();
                    LinkDown linkDown = JSONObject.parseObject(s1, LinkDown.class);
                    list = this.sysBaseAPI.queryTableDictItemsByCode(linkDown.getTable(), linkDown.getTxt(), linkDown.getKey());
                    hashMap.put(dbFieldName, list);
                    columnModel.setCustomRender(dbFieldName);
                    arrayList.add(columnModel);
                    String linkField = linkDown.getLinkField();
                    this.getIsShowList(onlCgformFields, arrayList3, arrayList, dbFieldName, linkField);
                }

                if ("sel_tree".equals(showType)) {
                    String[] dictTexts = onlCgformField.getDictText().split(",");
                    List tableDictItemsByCodes = this.sysBaseAPI.queryTableDictItemsByCode(onlCgformField.getDictTable(), dictTexts[2], dictTexts[0]);
                    hashMap.put(dbFieldName, tableDictItemsByCodes);
                    columnModel.setCustomRender(dbFieldName);
                }

                if ("cat_tree".equals(showType)) {
                    s1 = onlCgformField.getDictText();
                    if (oConvertUtils.isEmpty(s1)) {
                        String codeLike = SqlSymbolUtil.getCODELike(onlCgformField.getDictField());
                        list = this.sysBaseAPI.queryFilterTableDictInfo("SYS_CATEGORY", "NAME", "ID", codeLike);
                        hashMap.put(dbFieldName, list);
                        columnModel.setCustomRender(dbFieldName);
                    } else {
                        columnModel.setCustomRender("_replace_text_" + s1);
                    }
                }

                if ("sel_depart".equals(showType)) {
//                    list = this.sysBaseAPI.queryAllDepartBackDictModel();
                    list = null;
                    hashMap.put(dbFieldName, null);
                    columnModel.setCustomRender(dbFieldName);
                }

                if ("sel_user".equals(onlCgformField.getFieldShowType())) {
                    List tableDictItemsByCodes = this.sysBaseAPI.queryTableDictItemsByCode("SYS_USER", "REALNAME", "USERNAME");
                    hashMap.put(dbFieldName, tableDictItemsByCodes);
                    columnModel.setCustomRender(dbFieldName);
                }

                if (showType.indexOf("file") >= 0) {
                    columnModel.setScopedSlots(new CustomRenderModel("fileSlot"));
                } else if (showType.indexOf("image") >= 0) {
                    columnModel.setScopedSlots(new CustomRenderModel("imgSlot"));
                } else if (showType.indexOf("editor") >= 0) {
                    columnModel.setScopedSlots(new CustomRenderModel("htmlSlot"));
                } else if ("date".equals(showType)) {
                    columnModel.setScopedSlots(new CustomRenderModel("dateSlot"));
                } else if ("pca".equals(showType)) {
                    columnModel.setScopedSlots(new CustomRenderModel("pcaSlot"));
                }

                if (StringUtils.isNotBlank(onlCgformField.getFieldHref())) {
                    s1 = "fieldHref_" + dbFieldName;
                    columnModel.setHrefSlotName(s1);
                    arrayList1.add(new HrefSlots(s1, onlCgformField.getFieldHref()));
                }

                if ("1".equals(onlCgformField.getSortFlag())) {
                    columnModel.setSorter(true);
                }

                if (!"link_down".equals(showType)) {
                    arrayList.add(columnModel);
                }
            }
        }

        OnlineConfigModel onlineConfigModel = new OnlineConfigModel();
        onlineConfigModel.setCode(onlCgformHeadId);
        onlineConfigModel.setTableType(onlCgformHead.getTableType());
        onlineConfigModel.setFormTemplate(onlCgformHead.getFormTemplate());
        onlineConfigModel.setDescription(onlCgformHead.getTableTxt());
        onlineConfigModel.setCurrentTableName(onlCgformHead.getTableName());
        onlineConfigModel.setPaginationFlag(onlCgformHead.getIsPage());
        onlineConfigModel.setCheckboxFlag(onlCgformHead.getIsCheckbox());
        onlineConfigModel.setScrollFlag(onlCgformHead.getScroll());
        onlineConfigModel.setColumns(arrayList);
        onlineConfigModel.setDictOptions(hashMap);
        onlineConfigModel.setFieldHrefSlots(arrayList1);
        onlineConfigModel.setForeignKeys(arrayList2);
        onlineConfigModel.setHideColumns(onlineHideColumns);
        List buttonList = this.onlCgformHeadService.queryButtonList(onlCgformHeadId, true);
        ArrayList arrayList4 = new ArrayList();
        Iterator iterator1 = buttonList.iterator();

        while(iterator1.hasNext()) {
            OnlCgformButton onlCgformButton = (OnlCgformButton) iterator1.next();
            if (!onlineHideColumns.contains(onlCgformButton.getButtonCode())) {
                arrayList4.add(onlCgformButton);
            }
        }

        onlineConfigModel.setCgButtonList(arrayList4);
        OnlCgformEnhanceJs onlCgformEnhanceJs = this.onlCgformHeadService.queryEnhanceJs(onlCgformHeadId, "list");
        if (onlCgformEnhanceJs != null && oConvertUtils.isNotEmpty(onlCgformEnhanceJs.getCgJs())) {
            s = EnhanceJsUtil.getJsFunction(onlCgformEnhanceJs.getCgJs(), buttonList);
            onlineConfigModel.setEnhanceJs(s);
        }

        if ("Y".equals(onlCgformHead.getIsTree())) {
            onlineConfigModel.setPidField(onlCgformHead.getTreeParentIdField());
            onlineConfigModel.setHasChildrenField(onlCgformHead.getTreeIdField());
            onlineConfigModel.setTextField(onlCgformHead.getTreeFieldname());
        }

        return onlineConfigModel;
    }

    private void getIsShowList(List<OnlCgformField> onlCgformFields, List<String> strings, List<ColumnModel> columnModels, String dbFieldName, String linkField) {
        if (oConvertUtils.isNotEmpty(linkField)) {
            String[] linkFields = linkField.split(",");
            String[] linkFields1 = linkFields;
            int length = linkFields.length;

            for(int i = 0; i < length; ++i) {
                String linkField1 = linkFields1[i];
                Iterator iterator = onlCgformFields.iterator();

                while(iterator.hasNext()) {
                    OnlCgformField onlCgformField = (OnlCgformField) iterator.next();
                    String fieldName = onlCgformField.getDbFieldName();
                    if (1 == onlCgformField.getIsShowList() && linkField1.equals(fieldName)) {
                        strings.add(linkField1);
                        ColumnModel columnModel = new ColumnModel(onlCgformField.getDbFieldTxt(), fieldName);
                        columnModel.setCustomRender(dbFieldName);
                        columnModels.add(columnModel);
                        break;
                    }
                }
            }
        }

    }

    @Override
    public JSONObject queryOnlineFormObj(OnlCgformHead head, OnlCgformEnhanceJs onlCgformEnhanceJs) {
        JSONObject jsonObject = new JSONObject();
        String headId = head.getId();
        List availableFields = this.onlCgformFieldService.queryAvailableFields(head.getId(), head.getTableName(), (String)null, false);
        List disabledFields = this.onlCgformFieldService.queryDisabledFields(head.getTableName());
        EnhanceJsUtil.getCgJs(onlCgformEnhanceJs, availableFields);
        FieldModel fieldModel = null;
        if ("Y".equals(head.getIsTree())) {
            fieldModel = new FieldModel();
            fieldModel.setCodeField("id");
            fieldModel.setFieldName(head.getTreeParentIdField());
            fieldModel.setPidField(head.getTreeParentIdField());
            fieldModel.setPidValue("0");
            fieldModel.setHsaChildField(head.getTreeIdField());
            fieldModel.setTableName(SqlSymbolUtil.getSubstring(head.getTableName()));
            fieldModel.setTextField(head.getTreeFieldname());
        }

        JSONObject jsonObject1 = SqlSymbolUtil.getFiledJson(availableFields, disabledFields, fieldModel);
        jsonObject1.put("table", head.getTableName());
        jsonObject.put("schema", jsonObject1);
        jsonObject.put("head", head);
        List buttons = this.onlCgformHeadService.queryButtonList(headId, false);
        if (buttons != null && buttons.size() > 0) {
            jsonObject.put("cgButtonList", buttons);
        }

        if (onlCgformEnhanceJs != null && oConvertUtils.isNotEmpty(onlCgformEnhanceJs.getCgJs())) {
            String cgJs = EnhanceJsUtil.getCgJs(onlCgformEnhanceJs.getCgJs() , buttons);
            onlCgformEnhanceJs.setCgJs(cgJs);
            jsonObject.put("enhanceJs", EnhanceJsUtil.getCgJs(onlCgformEnhanceJs.getCgJs()));
        }

        return jsonObject;
    }

    @Override
    public JSONObject queryOnlineFormObj(OnlCgformHead head) {
        OnlCgformEnhanceJs onlCgformEnhanceJs = this.onlCgformHeadService.queryEnhanceJs(head.getId(), "form");
        return this.queryOnlineFormObj(head, onlCgformEnhanceJs);
    }

    private List<OnlCgformField> getOnlCgformField(String onlCgformHeadId) {
        LambdaQueryWrapper<OnlCgformField> onlCgformFields = new LambdaQueryWrapper();
        onlCgformFields.eq(OnlCgformField::getCgformHeadId, onlCgformHeadId);
        onlCgformFields.orderByAsc(OnlCgformField::getOrderNum);
        return this.onlCgformFieldService.list(onlCgformFields);
    }
}
